<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\mill\builder\Admin;
use app\mill\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Stat as StatModel;
use app\mill\model\Give as GiveModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 账单控制器
 * @package app\admin\controller
 */
class Finance extends Admin
{
    public $_status = [
        -1      =>  '未通过',
        0       =>  '待审核',
        1       =>  '已审核',
    ];

    //初始化
    protected function initialize(){
        parent::initialize();
        GiveModel::init();
    }

    //面积表计价统计
    public function archivesPriceIndexHtml(){
        $option = "{
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '15',
                            right: '15',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        yAxis : [
                            {
                                type : 'value',
                                axisLabel : {
                                    formatter: ''
                                }
                            }
                        ],
                        xAxis: {
                            type: 'category',
                            boundaryGap : false,
                            data: data.head
                        },
                        series: data.series
                    }";
        $url = url('mill/stat/ajaxArchivesPrice');
        $top_html = StatModel::topStatHtml($url,$option,['charts','year']);

        return $top_html;
    }

    //设定面积表初始价格列表
    public function archivesPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['archives_status','=',2];
        $map = array_merge($map);
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,s.staff as sales,c.company')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->leftJoin('mill_staff s','o.sales_id=s.id')
            ->where($map)
            ->group('o.id')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                $v = array_merge($v,$archvices);

                if($v['archives_sn'])$v['archives_sn'] = $v['archives_sn'].ClientModel::getTags($v);

                //开平信息
                $v['give_status_str'] = isset(GiveModel::$give_status[$v['give_status']])?GiveModel::$give_status[$v['give_status']]:'已完成';
                if($v['give_status'] > 0)$v['give_status_str'] .= '中';

                //油漆采购
                $v['order_color_sum'] = '';
                //周期
                $v['give_pro'] = empty($v['give_pro'])?'':"{$v['give_pro']}天";
                //计价
                $v['archives_price'] = '<a class="btn btn-default" href="javascript:void(0);">计价</a>';

                return $v;
            })
        ;

        $group_name = '工程列表';

        //获取生产状态字段
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        $columns2 = [];
        $column_width2 = [];
        foreach ($give_status as $gk=>$gs){
            $columns2[] = ["status{$gk}_no_sum", "待{$gs}(件)",'','','','badge-info',['group'=>'生产情况']];
            $column_width2["status{$gk}_no_sum"] = 53;
        }

        $columns = [ // 批量添加列
            ['archives_sn', '档案号','','','','badge-warning',['group'=>$group_name]],
            ['engineering', '工程名称','','','','',['group'=>$group_name]],
            ['batch', '批次','','','','',['group'=>$group_name]],
            ['number_sum', '数量(件)','','','','',['group'=>$group_name]],
            ['area_sum', '面积(㎡)','','','','',['group'=>$group_name]],
        ];
        $columns = array_merge($columns,$columns2);
        $columns2 = [
            ['archives_drawing', '面积表','files','','','badge-info',['group'=>'生产情况']],
            ['point_time', '交货时间','date','','','badge-info',['group'=>'生产情况']],
            ['area_ok_sum', '已发面积(M²)','','','','',['group'=>'发货情况']],
            ['area_no_sum', '未发面积(M²)','','','','',['group'=>'发货情况']],
            ['is_lock','冻结情况','status','',['工程冻结:warning', '工程启用:success'],'badge-warning',['group'=>'其他信息']],
            ['address_price','发货金额(元)','','','','badge-warning',['group'=>'工程计价']],
            ['initial_price','计价金额(元)','','','','badge-warning',['group'=>'工程计价']],
            ['right_button','计价','','','','badge-warning',['group'=>'工程计价']],
        ];
        $columns = array_merge($columns,$columns2);

        $column_width = [
            'id'  => 60,
            'archives_sn'  => 170,
            'number_sum'  => 40,
            'area_sum'  => 70,
            'status7_area'  => 70,
            'status7_area_no'  => 70,
            'address_price'  => 82,
            'initial_price'  => 82,
            'batch'  => 60,
            'order_color_sum'  => 50,
            'point_time'  => 70,
            'give_pro'  => 40,
            'is_lock'  => 80,
            'right_button'  => 50,
        ];
        $column_width = array_merge($column_width,$column_width2);

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('计价') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setExtraHtml($this->archivesPriceIndexHtml(),'block_top')
            //->hideCheckbox()
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称', 'o.back' => '内勤']) // 设置搜索参数
            ->setSearchArea([
                ['radio:5', 'o.mill_id', '','','',ClientModel::getMillList(),'left'],
            ])
            ->addColumns($columns)
            ->addTopButton('able',['title' => '清空扫码状态','href'=>url('mill/give/able',['status'=>0]),'class'=>'btn btn-default ajax-post confirm','target-form'=>'order_ids','float'=>'right'],false)
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addRightButton('archivesPrice',['title' => '计价','href' => url('mill/finance/archivesPrice',['order_id' => '__id__']),'class'=>'btn btn-default'],false)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth($column_width)
            ->fetch(); // 渲染模板
    }
    //设定面积表初始价格
    public function archivesPrice()
    {

        $order_id = input('order_id');//指定工程
        $print = input('print');//0:编辑 1:打印 2:导出
        if(empty($order_id))$this->error('错误操作');

        if ($this->request->isPost()) {
            $data = $this->request->post();

            //更新面积表开槽等信息
            if(!empty($data['archives_arr'])){
                foreach ($data['archives_arr'] as $aav){
                    $aav_id = $aav['id'];
                    unset($aav['id']);

                    if(!empty($aav_id))Db::name('mill_order_archives')->where('id='.$aav_id)->update($aav);
                }
            }
            //更新定价
            if(!empty($data['price_arr'])){
                foreach ($data['price_arr'] as $pav){
                    $pav_id = $pav['id'];
                    unset($pav['id']);

                    if(empty($pav_id))Db::name('mill_order_archives_initial_price')->insert($pav);
                    else Db::name('mill_order_archives_initial_price')->where('id='.$pav_id)->update($pav);
                }
            }
            //更新总计价金额和计价时间
            $order_add = [
                'initial_price'     =>  $data['initial_price'],
                'initial_time'      =>  $data['initial_time'],
            ];
            Db::name('mill_order')->where(['id'=>$order_id])->update($order_add);
            //更新发货金额
            FinanceModel::updateAddressPrice($order_id);

            $this->success('操作成功',cookie('__forward__'));
        }

        $where[] = ['a.order_id','=',$order_id];
        $join = [
            ['mill_order o','a.order_id=o.id','left'],
            ['mill_staff ms','o.sales_id=ms.id','left'],
            ['mill_client c','c.id=o.client_id','left']
        ];

        //单价设置
        $order = Db::name('mill_order_archives')
            ->alias('a')
            ->field('o.*,ms.staff as sales,c.company,c.mobile as c_mobile,group_concat(o.archives_sn) as archives_sns,group_concat(o.batch) as batchs,SUM(a.row_area) AS area_sum,SUM(a.number) AS number_sum,SUM(a.number*a.weld) AS weld,SUM(a.number*a.slot) AS slot,SUM(a.number*a.torque) AS torque')
            ->join($join)
            ->where($where)
            ->order('a.order_id asc,a.sort asc')
            ->find();

        //表头
        $order['table_head'][] = [
            "[3:1]<div class='dch-'>客户名称:{$order['company']}</div>",
            "[3:1]<div class='dch-'>工程名称:{$order['engineering']}</div>",
            "[2:1]<div class='dch-'>档案编号:{$order['archives_sn']}</div>",
            "[2:1]<div class='dch-'>批次:{$order['batch']}</div>",
            "[2:1]<div class='dch-'>业务经理:{$order['sales']}</div>",
            "[2:1]<div class='dch-'>内勤:{$order['back']}</div>",
        ];

        $archives_fields = [];
        foreach (ArchivesModel::$layui_fields as $lhv){
            $archives_fields["a.{$lhv['field']}"] = $lhv['title'];
        }
        $archives_fields['FROM_UNIXTIME(o.archives_bill_time,\'%Y-%m-%d\') as archives_bill_time'] = '来单日期';
        //面积表信息
        $order['table_archives']['head'] = array_values($archives_fields);
        $order['table_archives']['data'] = ArchivesModel::getList('',array_keys($archives_fields),'','',$join,$where);

        $title = "计价";

        //基本计价
        $order['table_archives_group']['head'] = ['厚度','颜色','铝板版型','合计数量(件)','合计面积(M²)','单价(元)','合计金额(元)'];
        $table_group_field = "a.thickness,a.color,a.model,SUM(a.number) AS number_sum,SUM(a.row_area) AS one_area_sum,group_concat(a.id) as archives_ids,a.order_id";
        $order['table_archives_group']['data'] = ArchivesModel::getList('',$table_group_field,'','a.thickness,a.color,a.model',$join,$where);

        //print 1:打印模式 2:导出模式
        if($print == 2){
            echo FinanceModel::toHtml($order,$print);exit;
        }

        $table_arr = FinanceModel::fromArchivesTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];
        $js = $table_arr['js'];
        $css = $table_arr['css'];

        $left_data = ['title'=>'计价','url'=>url('mill/finance/archivesprice'),'param'=>'order_id','back_url'=>cookie('__forward__')];
        $top_html = StatModel::ajaxLeftHtml($left_data,url('mill/stat/ajaxArchivesPriceList'));

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->setExtraHtml($top_html,'content_top')
            ->addHidden('initial_price',$order['initial_price'])
            ->addHidden('initial_time',time())
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'list_archives_group_title', '', $table_head, '',''],
                ['complexTable:12', 'list_archives_group', '', $table_data, '',''],
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->fetch();
    }


}
